using System;
using System.Collections.Generic;
using RomanJendrusz.Amazon.ETL.Infrastructure.Bus.RequestHandlers;
using RomanJendrusz.Amazon.ETL.Messages;
using System.Collections;
using RomanJendrusz.Amazon.ETL.Infrastructure.IoC;

namespace RomanJendrusz.Amazon.ETL.Infrastructure.Bus
{
    public class RequestHandlerFactory: IRequestHandlerFactory
    {
        private readonly Dictionary<string , Type> requestHandlers;

        public RequestHandlerFactory()
        {
            requestHandlers = new Dictionary<string, Type>();
            initHandlers();
        }

        private void initHandlers()
        {
            requestHandlers.Add(AwsDestinations.ItemLookup, typeof(ItemLookupRequestHandler));
            requestHandlers.Add(AwsDestinations.SellerListingLookup, typeof(SellerListingLookupRequestHandler));
        }


        public IRequestHandler GetRequestHandler(AmazonRequest forRequest)
        {
            if (forRequest == null) throw new ArgumentNullException("forRequest");
            return GetRequestHandler(forRequest.Destination);
        }

        public IRequestHandler GetRequestHandler(string destination)
        {
            if (destination == null) throw new ArgumentNullException("destination");
            return getHandler(destination);
        }

        private IRequestHandler getHandler(string destination)
        {
            if (requestHandlers.ContainsKey(destination) == false)
            {
                var message = string.Format("request message handler for operation {0} is not registred", destination);
                throw new InvalidOperationException(message);
            }
            var handlerType = requestHandlers[destination];
            return (IRequestHandler)IoCGateway.Resolve(handlerType);
        }
    }
}